const merchantModel = require('../models/merchantModel');
const mongoose = require('mongoose');
const create = async (ctx, next) => {
  const req = ctx.request.body;
  const data = Object.assign({status: 0, createDate: new Date()}, req);
  const result = await merchantModel.create(data);
  if (result) {
    ctx.body = {
      code: 1,
      msg: '添加成功！',
      data: {}
    };
  }
}

const findById = async (merchantId) => {
  const result = await merchantModel.findById(mongoose.Types.ObjectId(merchantId));
  return result;
}

const findMyMerchant = async (ctx, next) => {
  const condition = {
    owners: {
      $elemMatch: {
        $eq: ctx.state.user.userId
      }
    },
    status: {
      $gt: -1
    }
  };
  const result = await merchantModel.find(condition, null , {
    sort: {
      createDate: 'desc'
    }
  });
  if (result) {
    ctx.body = {
      code: 1,
      data: result
    };
  }
}

const find = async (ctx, next) => {
  const query = ctx.request.query;
  const name = query.name;
  const condition = {
    status: {
      $gt: -1
    }
  };
  if (name) {
    condition.name = {
      $regex: name
    }
  }
  const result = await merchantModel.find(condition, null , {
    sort: {
      createDate: 'desc'
    }
  });
  if (result) {
    ctx.body = {
      code: 1,
      data: result
    };
  }
}

const update = async (ctx, next) => {
  const req = ctx.request.body;
  const result = await merchantModel.update({
    _id: req._id
  }, req);
  if (result) {
    ctx.body = {
      code: 1,
      msg: '修改成功！',
      data: {}
    };
  }
}

module.exports = {
  create,
  find,
  update,
  findMyMerchant,
  findById
};